package com.venn.interceptor;

import com.alibaba.druid.util.StringUtils;
import com.venn.controller.UserController;
import com.venn.entity.User;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by venn on 2/22/17.
 */
public class LoginCheckInterceptor implements HandlerInterceptor {
    private static Logger logger = LogManager.getLogger(UserController.class.getName());
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        //获取请求的URL
        String url = httpServletRequest.getRequestURI();
        //URL:login.jsp是公开的;这个demo是除了login.jsp是可以公开访问的，其它的URL都进行拦截控制
        if(url.indexOf("login.do")>=0){
            return true;
        }

        User user = (User)httpServletRequest.getSession().getAttribute("user");

        logger.info("put user : "+user +" to session");
        if(user == null){
//            httpServletResponse.sendRedirect("/index");//跳转登录页面

            httpServletRequest.getRequestDispatcher("/WEB-INF/index.jsp").forward(httpServletRequest, httpServletResponse);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
